<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { Form } from 'ant-design-vue';
import { postSysRoleApi } from '@/common/apis/role'

const open = ref<boolean>(false);
const useForm = Form.useForm;
const roleState = ref(false)
const labelCol = { span: 4 };
const wrapperCol = { span: 14 };

// 数据
const formState = reactive({
    name: '',  // 角色名称
    state: roleState.value === true ? 1 : 0, // 角色状态
    description: ''  // 角色描述
});

// 清空表单数据
const resetFormState = () => {
    formState.name = ''; // 清空角色名称
    formState.state = roleState.value === true ? 1 : 0; // 重置角色状态
    formState.description = ''; // 清空角色描述
};

const props = defineProps({
    getStyRoleData: {
        type: Function,
        required: true,
    },
})


const showModal = () => {
    open.value = true;
};

// 规则校验
const rules = reactive({
    name: [{ required: true, message: '请输入角色', }],
    description: [{ required: true, message: '请输入内容', trigger: 'blur' }],
});


const { resetFields, validate, validateInfos } = useForm(formState, rules, {
    onValidate: (...args) => console.log(...args),
});

// 点击确认按钮
const onSubmit = async () => {
    await validate()
    const res = await postSysRoleApi(formState)
    console.log(res, '新增角色')
    resetFormState()
    open.value = false
    // 刷新数据
    await props.getStyRoleData()  // 触发父组件的事件
    message.success('新增部门成功');
};

defineExpose({ showModal })
</script>

<template>
    <div>
        <a-modal v-model:open="open" title='新增角色' @ok="onSubmit" @cancel="resetFields">
            <a-form :label-col="labelCol" :wrapper-col="wrapperCol" :model="formState" :rules="rules">
                <a-form-item label="角色名称" v-bind="validateInfos.name">
                    <a-input placeholder='请输入名称' v-model:value="formState.name" />
                </a-form-item>
                <a-form-item label="启用" name="delivery">
                    <a-switch v-model:checked="formState.state" />
                </a-form-item>
                <a-form-item label="角色描述" name="description" v-bind="validateInfos.description">
                    <a-textarea placeholder='简介' v-model:value="formState.description" />
                </a-form-item>
            </a-form>

        </a-modal>
    </div>
</template>
